package org.ddd.book.domain.factoty;

import cn.hutool.extra.spring.SpringUtil;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class MyBeanUtil {

    @SuppressWarnings("all")
    private final static ConcurrentHashMap<Class, Object> CACHE = new ConcurrentHashMap<>();

    public static <T> T getBean(Class<T> beanClass) {
        try {
            T bean = SpringUtil.getBean(beanClass);
            if (null != bean) {
                return bean;
            }
        } catch (Exception e) {
            log.warn("been not found! class = {}", beanClass.getName());
        }
        // 为了防止bean没有注册而造成程序出错，动态生成一个（目的是为了方便测试领域层）
        Object proxyInstance = CACHE.get(beanClass);
        if (null == proxyInstance) {
            proxyInstance = Proxy.newProxyInstance(RepositoryFactory.class.getClassLoader(), new Class[]{beanClass}, new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    return null;
                }
            });
            CACHE.put(beanClass, proxyInstance);
        }
        return (T) proxyInstance;
    }

}
